# coding=utf-8
import sys, json, re, os

def create_exam(tex_file):
    fd = open(tex_file, encoding="utf-8")
    # print (fd.readlines())
    p1 = re.compile(r'{.*?}', re.S) 
    p2 = re.compile(r'{.*?}', re.S) 
    lines = fd.readlines()
    title = lines[0]
    record_date = lines[1]
    # print (title, record_date)    
    title  = re.findall(p1, title)[0][1:-1]
    record_date = re.findall(p2, record_date)[0][1:]
    content_body = lines[2:]
    bold_content_body = []
    return title , record_date , content_body


def read_template(template_file):
    fd = open(template_file, "r", encoding="utf-8")
    # content = fd.read()
    # print (content)
    stage = "stop"
    header = []
    body = []
    for line in fd:
        # print(line)
        if stage == "stop":  
            line = line.strip()
            if line == "header":
                stage = "header"
                continue
        elif stage == "header":
            line = line.strip()
            if line == "body":
                stage = "body"
                continue
            if len(line):
                # print ("header:", line)
                header.append(line)
        elif stage == "body":
            line = line.strip()
            if len(line):
                # print("body:", line)
                body.append(line)            
        else:
            print("wrong")
    fd.close()
    # print(header)
    # print(body)
    return header, body

def write_template_header(fd, header_list):
    for h in header_list:
        fd.write(h + "\n")

def write_template_body(fd, body_list):
    for h in body_list:
        fd.write(h + "\n")

def latex_to_pdf(tex_filename):
    """
    在output目录，将tex文件转化为pdf文件
    """
    cmd = "xelatex  -output-directory ./output " + output_tex
    os.system (cmd)
    os.system("mv ./output/*.pdf .")
    # os.system ("rm -rf ./output/*")
    # os.system("mv  ./*.pdf ./output/")    


if __name__ == "__main__":

    if len(sys.argv) == 3:
        grade_num = sys.argv[1]
        exam_num = sys.argv[2]
        output_tex = "./output/grade" + grade_num + "_" + exam_num + ".tex"
        input_tex_file = "./grade" + str(grade_num) + "/tex/section" + str(exam_num) +".tex"
        print("#####", input_tex_file)
        title, record_date, content_body = create_exam(input_tex_file)
        template = "../template/paper.json"
        header, body = read_template(template)
        fd = open(output_tex, "w", encoding="utf-8")
        write_template_header(fd, header)
        title = "\\title{\\vspace{-3cm}" + title + "}\n"
        print (record_date)
        record_date = "\\date{\\vspace{-1.2cm}" + record_date + "}\n"    
        fd.write(title)
        fd.write(record_date)
        fd.write("\\author{\\large  猫姐 \\\\ \\large 试卷整理人 \\and \\large 高炀 \\\\ \\large 做题人}\n")
    
        write_template_body(fd, body)
        write_template_body(fd, content_body)
        fd.write("\\end{document}")
        fd.close()
        # print("****************Creating pdf file")
        latex_to_pdf(output_tex)

        # 加上头latex模板信息
        # 输出latex
        # 调用xelate生成pdf


    else:
        print("wrong args")


        # python get_math.py  1 1 && xelatex exam.tex